<?php

namespace Home\Controller;

use Common\Top;
use Common\Utils;
use Common\Sms;
use Think\Controller;

class AgencyController extends CommonController
{


    public function details()
    {
        $id = I('id', 0, 'int');
        $today = date('Y-m-d 00:00:00');

        $skuInfo = M('tour_sku')->where("tour_id = '{$id}' && start_time >= '{$today}'")->select();

        if ($skuInfo[0]['cruise']) {
            $cruise = array();
            foreach ($skuInfo as $key => $vo) {
                $cruise[] = explode(';', $vo['cruise']);
            }

            $cruiseArr = array();
            foreach ($cruise as $key => $v) {
                $v = array_filter($v);
                foreach ($v as $k => $vo) {
                    $cruiseArr[$key][$k] = explode(',', $vo);
                }
            }

            $this->assign('cruiseArr', $cruiseArr);
        }


        $list = M('tour')->where("id = '{$id}'")->find();

        $agencyId = $this->userInfo['id'];
        //get min_price
        $now = date("Y-m-d 00:00:00");
        $agencyTourList = M('agency_tour_price')->where("agency_id = '{$agencyId}' && tour_id = '{$id}' && start_time >= '{$now}'")->field('agency_id,tour_id,min(price_adult_list) price_adult_list')->group('tour_id')->find();
        //获取该线路是否被该顾问修改分享标题
        $agencyTourTitle = M('agency_tour_title')->where("agency_id = '{$agencyId}' && tour_id = '{$id}'")->field('id,title')->find();
        if ($agencyTourList) {
            $list['min_price'] = min($list['min_price'], $agencyTourList['price_adult_list']);
        }

        $departure = explode(" ", $list['departure']);
        if ($departure['0'] == $departure['1']) {
            unset($departure['1']);
            $departure = implode(" ", $departure);
        } else {
            $departure = implode(" ", $departure);
        }

        $Pics = explode("@@@", $list['pics']);
        array_pop($Pics);

        $picArr = array();
        foreach ($Pics as $vo) {
            $picArr[] = Utils::GetImageUrl(str_replace("#file1#", C('FILE1_BASE_URL'), substr($vo, 0, strpos($vo, '|'))), 300, 300, 1);
        }

        $bgImg = $picArr[0];
        //行程安排
        $tour_description = M('tour_plan as p')
            ->where("p.tour_id = '{$id}'")
            ->order('p.day asc')
            ->field(array(
                'p.day' => 'day',
                'p.description' => 'description',
                'p.hotel' => 'hotel',
                'p.dining' => 'dining',
            ))
            ->select();
        //出行天数
        $totalDay = count($tour_description);

        //查询位控表
        $tourSku = M('tour_sku')->where("tour_id = '{$id}' && start_time >= '{$today}'")->order("start_time desc")->select();

        //查询改价表是否改价
        $agencyTourPrice = M('agency_tour_price')->where("agency_id = '{$agencyId}' && tour_id = '{$id}'")->select();

        if ($agencyTourPrice) {
            foreach ($agencyTourPrice as $k => $v) {
                foreach ($tourSku as $key => $vo) {
                    if ($v['sku_id'] == $vo['id']) {
                        $tourSkuDate[$key]['id'] = $vo['id'];
                        $tourSkuDate[$key]['price_adult_list'] = $v['price_adult_list'];
                        $tourSkuDate[$key]['start_time'] = substr($vo['start_time'], 0, 10);
                        $tourSkuDate[$key]['price_adult_agency'] = $vo['price_adult_agency'];
                    }
                }
            }
        } else {
            foreach ($tourSku as $key => $vo) {
                $tourSkuDate[$key]['id'] = $vo['id'];
                $tourSkuDate[$key]['price_adult_list'] = $vo['price_adult_list'];
                $tourSkuDate[$key]['start_time'] = substr($vo['start_time'], 0, 10);
                $tourSkuDate[$key]['price_adult_agency'] = $vo['price_adult_agency'];
            }
        }

        $domain = $_SERVER['SERVER_NAME'];
        $domain = "http://" . $domain . "/index.php/Home/Agency/details/id/{$id}.html";
        $this->assign('domain', $domain);

        $this->assign('bgImg', $bgImg);
        $this->assign('departure', $departure);
        $this->assign('agencyTourTitle', $agencyTourTitle);
        $this->assign('tourSkuDate', $tourSkuDate);
        $this->assign('tour_description', $tour_description);
        $this->assign('totalDay', $totalDay);
        $this->assign('list', $list);
        $this->assign('tourList', $list);
        $this->assign('picArr', $picArr);
        $this->assign('tourSku', $tourSku);
        $this->assign('today', $today);

        $this->display();
    }

    //顾问推荐线路产品方法
    public function recommend()
    {
        if (IS_AJAX && IS_POST) {
            //获取顾问身份
            $userList = $this->userInfo;
            $data['tour_id'] = I('tour_id');
            $data['agency_id'] = $userList['id'];
            $data['create_time'] = date('Y-m-d H:i:s', time());
            $tourId['tour_id'] = I('tour_id');
            $agencyId = $userList['id'];

            $indexIds = session('indexIds');

            if (strpos($tourId['tour_id'], $indexIds) === false || empty($indexIds)) {
                $list = M('agency_tour')->where($tourId)->where("agency_id = '{$agencyId}'")->find();

                if (empty($list)) {
                    M('agency_tour')->add($data);
                    $data['status'] = 1;
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '您已推荐该产品';
                    $this->ajaxReturn($data);
                }
            } else {
                $data['status'] = 0;
                $data['msg'] = '产品已在首页';
                $this->ajaxReturn($data);
            }
        }
    }

    /**
     * [orderMoney ajax改变价钱]
     */
    public function orderMoney()
    {
        if (IS_AJAX && IS_POST) {
            $where['start_time'] = I('startTime');
            $where['tour_id'] = I('id');
            $list = M('tour_sku')->field('price_adult_agency,price_child_agency,price_hotel_agency,price_adult_list')->where($where)->find();
            $list['price_adult_agency'] = Utils::getYuan($list['price_adult_agency']);
            $list['price_child_agency'] = Utils::getYuan($list['price_child_agency']);
            $list['price_hotel_agency'] = Utils::getYuan($list['price_hotel_agency']);
            $list['price_adult_list'] = Utils::getYuan($list['price_adult_list']);
            $this->ajaxReturn($list);
        }
    }

//改价
    public function changePrice()
    {
        $M = M();
        $userList = $this->userInfo;

        if (IS_AJAX && IS_POST) {
            $data = I('postData');
            //按逗号分割
            $dataList = explode(',', $data);
            //去除最后一个
            $info = rtrim($data, '');
            // 删除最后一个 
            array_pop($dataList);
            //统计长度
            $count = count($dataList);
            //判断该有几条数据 9为一个id数据
            $count = $count / 9;
            //组装成二位数组
            for ($i = 0; $i < $count; $i++) {
                $dataArr[$i]['sku_id'] = $dataList[$i * 9];
                $dataArr[$i]['price_adult_list'] = Utils::getFen($dataList[$i * 9 + 2]);
                $dataArr[$i]['price_child_list'] = Utils::getFen($dataList[$i * 9 + 5]);
                $dataArr[$i]['price_hotel_list'] = Utils::getFen($dataList[$i * 9 + 8]);
                $dataArr[$i]['create_time'] = date('Y-m-d H:i:s', time());
                $skuList = M('tour_sku')->where("id=" . $dataArr[$i]['sku_id'] . "")->field('id,tour_id,start_time')->limit(1)->find();
                M('agency_tour_price')->where("tour_id=" . $skuList['tour_id'] . "")->delete();
                $dataArr[$i]['tour_id'] = $skuList['tour_id'];
                $dataArr[$i]['start_time'] = $skuList['start_time'];
                $dataArr[$i]['agency_id'] = $userList['id'];
            }
            //数据存入
            $list = M('agency_tour_price')->addAll($dataArr);

            if ($list) {
                echo '1';
            } else {
                echo '0';
            }
        } else {
            $isLogin = session('isLogin');
            if ($isLogin == 'yes') {
                $id = I('id', 0, 'int');

                $tour_list = $M->table('top_tour')
                    ->where("id='{$id}'")
                    ->field('id,name,min_price,cover_pic,line_type,travel_type')
                    ->find();

                $agencyId = $userList['id'];

                //查看是否改价
                $now = date("Y-m-d 00:00:00");
                $agencyTourList = M('agency_tour_price')->where("agency_id = '{$agencyId}' && tour_id = '{$id}' && start_time >= '{$now}'")->field('id,agency_id,sku_id,tour_id,min(price_adult_list) price_adult_list,min(price_child_list) price_child_list')->group('tour_id')->find();

                if ($agencyTourList) {
                    $tour_list['min_price'] = min($tour_list['min_price'], $agencyTourList['price_adult_list']);
                }

                $lineType = $tour_list['line_type'];

                if ($lineType == 1) {
                    $lineTypeName = '周边游';
                } else if ($lineType == 2) {
                    $lineTypeName = '国内游';
                } else if ($lineType == 3) {
                    $lineTypeName = '出境游';
                }

                $pic = substr($tour_list['cover_pic'], 0, 7);
                $picUrl = str_replace($pic, C('FILE1_BASE_URL'), $tour_list['cover_pic']);
                $pic = Utils::GetImageUrl($picUrl, 240, 160, 1);

                $tour_list['min_price'] = Utils::getYuanEdit($tour_list['min_price']);

                $list = $M->table('top_tour_sku as s')
                    ->where("s.tour_id = '{$id}'")
                    ->field(array(
                        's.id' => 'id',
                        's.tour_id' => 'tour_id',
                        's.start_time' => 'start_time',
                        's.price_child_agency' => 'price_child_agency',
                        's.price_adult_agency' => 'price_adult_agency',
                        's.price_hotel_list' => 'price_hotel_list',
                        's.price_hotel_agency' => 'price_hotel_agency',
                        's.price_child_list' => 'price_child_list',
                        's.price_adult_list' => 'price_adult_list',
                        's.cruise' => 'cruise',
                    ))
                    ->order("start_time desc")
                    ->select();

                $agencyId = $userList['id'];
                //查看是否改价
                $agencyTourList = M('agency_tour_price')->where("agency_id = '{$agencyId}' && tour_id = '{$id}'")->field('id,agency_id,sku_id,tour_id,price_adult_list,price_child_list,price_hotel_list')->select();

                if ($agencyTourList) {
                    foreach ($agencyTourList as $k => $v) {
                        foreach ($list as $key => $value) {
                            if ($v['sku_id'] == $value['id']) {
                                $list[$key]['user_defined_adult_list'] = Utils::getYuanEdit($v['price_adult_list']);
                                $list[$key]['user_defined_child_list'] = Utils::getYuanEdit($v['price_child_list']);
                                $list[$key]['user_defined_hotel_list'] = Utils::getYuanEdit($v['price_hotel_list']);
                                $list[$key]['price_child_agency'] = Utils::getYuanEdit($value['price_child_agency']);
                                $list[$key]['price_adult_agency'] = Utils::getYuanEdit($value['price_adult_agency']);
                                $list[$key]['price_hotel_list'] = Utils::getYuanEdit($value['price_hotel_list']);
                                $list[$key]['price_hotel_agency'] = Utils::getYuanEdit($value['price_hotel_agency']);
                                $list[$key]['price_adult_list'] = Utils::getYuanEdit($value['price_adult_list']);
                                $list[$key]['price_child_list'] = Utils::getYuanEdit($value['price_child_list']);
                                $list[$key]['start_time'] = substr($value['start_time'], 0, 10);
                            }
                        }
                    }
                } else {
                    foreach ($list as $key => $value) {
                        $list[$key]['price_child_agency'] = Utils::getYuanEdit($value['price_child_agency']);
                        $list[$key]['price_adult_agency'] = Utils::getYuanEdit($value['price_adult_agency']);
                        $list[$key]['price_hotel_list'] = Utils::getYuanEdit($value['price_hotel_list']);
                        $list[$key]['price_hotel_agency'] = Utils::getYuanEdit($value['price_hotel_agency']);
                        $list[$key]['price_adult_list'] = Utils::getYuanEdit($value['price_adult_list']);
                        $list[$key]['price_child_list'] = Utils::getYuanEdit($value['price_child_list']);
                        $list[$key]['start_time'] = substr($value['start_time'], 0, 10);
                    }
                }

                $this->assign('lineTypeName', $lineTypeName);
                $this->assign('pic', $pic);
                $this->assign('list', $list);
                $this->assign('tour_list', $tour_list);

                $this->display();
            } else {
                $id = I('id');
                $url = "http://" . $_SERVER['SERVER_NAME'] . "/index.php/Home/Agency/details/id/" . $id . ".html";
                header("Location:" . $url);
            }
        }
    }

//改分享标题
    public function changeTitle(){
        $M = M();
         $userList = $this->userInfo;

        if (IS_AJAX && IS_POST) {
            $tour_id = I('tour_id');
            $shareTitle = I('shareTitle');
            $agencyId = $userList['id'];
             $agencyTourTitle = M('agency_tour_title')->where("agency_id = '{$agencyId}' && tour_id = '{$tour_id}'")->field('id')->find();
             if($agencyTourTitle['id']){
            $data['title'] = $shareTitle;
            $data['update_time'] = date('Y-m-d H:i:s', time());
            //数据存入
            $list = M('agency_tour_title')->where('id='.$agencyTourTitle['id'])->save($data);
             }else{
                   $data['agency_id'] = $agencyId;
            $data['tour_id'] = $tour_id;
            $data['title'] = $shareTitle;
            $data['create_time'] = date('Y-m-d H:i:s', time());
            //数据存入
            $list = M('agency_tour_title')->add($data);
             }
          
            if ($list) {
                echo '1';
            } else {
                echo '0';
            }
        }else{
          $isLogin = session('isLogin');
            if ($isLogin == 'yes') {
                $id = I('id', 0, 'int');

                $tour_list = $M->table('top_tour')
                    ->where("id='{$id}'")
                    ->field('id,name,min_price,cover_pic,line_type,travel_type')
                    ->find();

                $agencyId = $userList['id'];

                //查看是否改价
                $now = date("Y-m-d 00:00:00");
                $agencyTourList = M('agency_tour_price')->where("agency_id = '{$agencyId}' && tour_id = '{$id}' && start_time >= '{$now}'")->field('id,agency_id,sku_id,tour_id,min(price_adult_list) price_adult_list,min(price_child_list) price_child_list')->group('tour_id')->find();
                //查看之前是否对该线路修改过分享标题
                $agencyTourTitle = M('agency_tour_title')->where("agency_id = '{$agencyId}' && tour_id = '{$id}'")->field('id,agency_id,tour_id,title')->find();
                if ($agencyTourList) {
                    $tour_list['min_price'] = min($tour_list['min_price'], $agencyTourList['price_adult_list']);
                }

                $lineType = $tour_list['line_type'];

                if ($lineType == 1) {
                    $lineTypeName = '周边游';
                } else if ($lineType == 2) {
                    $lineTypeName = '国内游';
                } else if ($lineType == 3) {
                    $lineTypeName = '出境游';
                }

                $pic = substr($tour_list['cover_pic'], 0, 7);
                $picUrl = str_replace($pic, C('FILE1_BASE_URL'), $tour_list['cover_pic']);
                $pic = Utils::GetImageUrl($picUrl, 240, 160, 1);
                $tour_list['min_price'] = Utils::getYuanEdit($tour_list['min_price']);
                $this->assign('pic', $pic);
                $this->assign('lineTypeName', $lineTypeName);
                $this->assign('agencyTourTitle', $agencyTourTitle);
                $this->assign('tour_list', $tour_list);
                $this->display();
            } else {
                $id = I('id');
                $url = "http://" . $_SERVER['SERVER_NAME'] . "/index.php/Home/Agency/details/id/" . $id . ".html";
                header("Location:" . $url);
            }
        }
        
    }
    public function morePics()
    {
        $id = I('get.id');
        $list = M('tour')->where("id = '{$id}'")->find();
        $Pics = explode("@@@", $list['pics']);
        array_pop($Pics);
        $picArr = array();

        foreach ($Pics as $vo) {
            $picArr[] = array(
                'img' => Utils::GetImageUrl(str_replace("#file1#", C('FILE1_BASE_URL'), substr($vo, 0, strpos($vo, '|'))), 600, 800, 0),
                'name' => substr($vo, strpos($vo, '|') + 3)
            );
        }

        $this->assign('list', $list);
        $this->assign('picArr', $picArr);
        $this->display();
    }


    public function orderInfo()
    {
        $M = M();
        $userList = $this->userInfo;
        $isLogin = session('isLogin');

        if ($isLogin == 'yes') {
            if (IS_POST && IS_AJAX) {
                if ($userList['account_state'] != '1') {
                    $data['status'] = 0;
                    $data['msg'] = '账户被冻结';
                    $this->ajaxReturn($data);
                }

                $postCode = I('code');
                $code = I('code');

                if ($postCode == $code) {
                    $id = I('id');
                    $keyid = Utils::getDecrypt(I('keyid'));

                    if ($id != $keyid) {
                        $data['status'] = 0;
                        $data['msg'] = '提交失败';
                        $this->ajaxReturn($data);
                    }

                    session('orderInfoCode', null);
                    $tourInfo = M('tour')->where("id='{$id}'")->find();

                    $providerId['id'] = $tourInfo['provider_id'];
                    $providerInfo = M('provider')->where($providerId)->field('id,commission_rate,operator_id,full_name')->find();

                    $data['commission_rate'] = $providerInfo['commission_rate'];
                    $data['tour_id'] = $id;
                    $data['agency_name'] = $userList['name'];
                    $data['tour_name'] = $tourInfo['name'];
                    $data['agency_id'] = $userList['id'];
                    $data['client_adult_count'] = I('client_adult_count');
                    $data['client_child_count'] = I('client_child_count');
                    $data['hotel_count'] = I('hotel_count');
                    $data['start_time'] = I('start_time');
                    $data['create_time'] = date('Y-m-d H:i:s', time());
                    $data['provider_id'] = $tourInfo['provider_id'];
                    $data['provider_name'] = $tourInfo['provider_name'];
                    $data['provider_full_name'] = $providerInfo['full_name'];
                    $data['provider_operator_id'] = $providerInfo['operator_id'];
                    $data['agency_operator_id'] = $userList['operator_id'];
                    $data['order_sn'] = substr(date("YmdHis", time()) . rand(1000, 9999), 2);
                    $where['start_time'] = I('start_time');
                    $where['tour_id'] = $tourInfo['id'];

                    //查找 top_tour_sku 表的提交日期信息
                    $sku_list = M('tour_sku')->where($where)->find();

                    $data['tour_sku_id'] = $sku_list['id'];
                    $data['price_adult'] = $sku_list['price_adult_agency'];
                    $data['price_child'] = $sku_list['price_child_agency'];
                    $data['price_hotel'] = $sku_list['price_hotel_agency'];
                    $data['contacts'] = I('contacts');
                    $data['contact_phone'] = I('contact_phone');
                    $data['memo'] = I('memo');
                    $data['state'] = Top::OrderStateSubmitted;

                    //计算成人、儿童总人数
                    $data['client_total'] = $data['client_adult_count'] + $data['client_child_count'];

                    $adult_amount = $data['price_adult'] * $data['client_adult_count'];
                    $child_amount = $data['price_child'] * $data['client_child_count'];
                    $hotel_amount = $data['price_hotel'] * $data['hotel_count'];

                    //coupon
                    $couponPrice = 50000;
                    $coupon = I('coupon');

                    if ($coupon == '1') {
                        $data['price_total'] = $adult_amount + $child_amount + $hotel_amount - $couponPrice;
                    } else {
                        $data['price_total'] = $adult_amount + $child_amount + $hotel_amount;
                    }

                    //将计算出的金额转成 **分
                    $totalMoney = $data['price_total'];

                    $result = $M->table('top_order_tour')->add($data);

                    //coupon order_id order_type 存入
                    if ($coupon == '1') {
                        $entityId = $userList['id'];
                        $couponStateNotUsed = Top::CouponStateNotUsed;
                        $couponInfo = M('promotion_coupon')->where("agency_id = '{$entityId}' && state = '{$couponStateNotUsed}'")->find();
                        $couponId = $couponInfo['id'];

                        $couponData['order_id'] = $result;
                        $couponData['order_type'] = 1;
                        $couponData['state'] = Top::CouponStateUsed;
                        M('promotion_coupon')->where("id = '{$couponId}'")->save($couponData);
                    }

                    $tourName = $tourInfo['name'];
                    $tourContactPhone = $tourInfo['contact_phone'];
                    $agencyName = $userList['name'];
                    $agencyId = $userList['id'];
                    $agencyNum = '(' . str_pad($agencyId, 4, '0', STR_PAD_LEFT) . ')';
                    $content = '您的' . $tourName . '线路已被代理商' . $agencyName . '' . $agencyNum . '预定，请登录系统查看';
                    Sms::Send($tourContactPhone, $content, $this->cdkey, $this->pwd, $this->signature, $this->smsOperatorId);

                    $tourOrderInfo = M('order_tour')->where("id = '{$result}'")->find();
                    $userInfo = M('user')->where("id = " . $tourInfo['user_id'])->find();
                    $notifyMsgTypes = explode(",", $userInfo['notify_msg_types']);
                    array_shift($notifyMsgTypes);
                    array_pop($notifyMsgTypes);
                    $transactionMessage = $notifyMsgTypes[1];

                    $template = array(
                        'touser' => $userInfo['weixinmp_openid'],
                        'template_id' => Utils::orderCreateSuccessTemplateId(),

                        'data' => array(
                            'first' => array('value' => urlencode($content), 'color' => "#000"),
                            'keyword1' => array('value' => urlencode($tourOrderInfo['order_sn']), 'color' => "#000"),
                            'keyword2' => array('value' => urlencode(Utils::getYuan($tourOrderInfo['price_total'])), 'color' => '#000'),
                            'keyword3' => array('value' => urlencode('已提交'), 'color' => '#000'),
                            'keyword4' => array('value' => urlencode($tourOrderInfo['create_time']), 'color' => '#000'),
                            'keyword5' => array('value' => urlencode($tourOrderInfo['tour_name']), 'color' => '#000'),
                            'remark' => array('value' => urlencode(''), 'color' => '#000'),
                        )
                    );

                    if ($transactionMessage) {
                        $this->send_tpl($template);
                    }

                    $orderLogData['order_id'] = $tourOrderInfo['id'];
                    $orderLogData['user_id'] = $tourOrderInfo['agency_id'];
                    $orderLogData['user_name'] = $tourOrderInfo['agency_name'];

                    if ($coupon == '1') {
                        $orderLogData['content'] = '代理商' . $agencyName . '下单,使用了1张500的代金券';
                    } else {
                        $orderLogData['content'] = '代理商' . $agencyName . '下单';
                    }

                    $orderLogData['amount'] = 0;
                    $orderLogData['create_time'] = date('Y-m-d H:i:s', time());
                    $orderLogData['payable_total'] = $totalMoney;
                    $orderLogData['remark'] = I('memo');

                    $orderLogResult = M('log_order_tour')->add($orderLogData);

                    if ($result && $orderLogResult) {
                        $data['status'] = 1;
                        $data['msg'] = '提交成功';
                        $this->ajaxReturn($data);
                    } else {
                        $data['status'] = 2;
                        $data['msg'] = '提交失败';
                        $this->ajaxReturn($data);
                    }
                } else {
                    $data['status'] = 3;
                    $data['msg'] = '请勿重复提交';
                    $this->ajaxReturn($data);
                }
            } else {
                $id = I('id', 0, 'int');
                $today = date('Y-m-d 00:00:00');
                $list = $M->table('top_tour as t,top_tour_sku as s')
                    ->where("t.id = $id && t.id = s.tour_id && s.start_time >= '{$today}'")
                    ->field(array(
                        't.id' => 'id',
                        't.name' => 'name',
                        't.traffic_go' => 'traffic_go',
                        't.traffic_back' => 'traffic_back',
                        't.min_price' => 'min_price',
                        't.departure' => 'departure',
                        't.destination' => 'destination',
                        't.code' => 'code',
                        's.price_child_agency' => 'price_child_agency',
                        's.price_adult_agency' => 'price_adult_agency',
                        's.price_hotel_agency' => 'price_hotel_agency',
                        's.start_time' => 'start_time',
                    ))
                    ->order('s.start_time desc')
                    ->find();

                $tourId = $list['id'];
                $list['price_adult_agency'] = Utils::getYuan($list['price_adult_agency']);
                $list['price_child_agency'] = Utils::getYuan($list['price_child_agency']);
                $list['price_hotel_agency'] = Utils::getYuan($list['price_hotel_agency']);

                //出游时间
                $tour_date = $M->table('top_tour_sku as s')
                    ->where("s.tour_id = '{$tourId}' && s.start_time >= '{$today}'")
                    ->field(array(
                        's.id' => 'id',
                        's.start_time' => 'start_time',
                    ))
                    ->order("start_time desc")
                    ->select();


                $agencyId = $userList['id'];
                $state = Top::CouponStateNotUsed;
                $couponInfo = M('promotion_coupon')->where("agency_id = '{$agencyId}' && state = '{$state}'")->find();
                $couponNum = count(M('promotion_coupon')->where("agency_id = '{$agencyId}' && state = '{$state}'")->field('id')->select());

                $filter = $couponInfo['filter'];
                $codeReturn = strpos($filter, $list['code']);

                if ($codeReturn) {
                    $codeName = '1';
                } else {
                    $codeName = '0';
                }

                $_SESSION['orderInfoCode'] = 400;

                $key = '双十一';
                $policyInfo = M("promotion_policy")->where("keyword = '{$key}'")->find();
                $startDate = '20151111000000';
                $endDate = '20160101000000';
                $nowDate = date("Ymd000000", time());

                $coupon = 500;
                $this->assign('coupon', $coupon);
                $this->assign('userList', $userList);
                $this->assign('list', $list);
                $this->assign('tour_date', $tour_date);
                $this->assign('nowDate', $nowDate);
                $this->assign('startDate', $startDate);
                $this->assign('endDate', $endDate);
                $this->assign('filter', $filter);
                $this->assign('codeName', $codeName);
                $this->assign('couponNum', $couponNum);
                $this->assign('policyInfo', $policyInfo);
            }
        } else {
            $domain = $_SERVER['SERVER_NAME'];
            $url = "http://" . $domain . "/index.php";
            header("Location:" . $url);
        }
        $this->display();
    }


    public function orderCruiseInfo()
    {
        $M = M();
        $userList = $this->userInfo;
        $isLogin = session('isLogin');

        if ($isLogin == 'yes') {
            if (IS_POST && IS_AJAX) {
                if ($userList['account_state'] != 1) {
                    $data['status'] = 0;
                    $data['msg'] = '账户被冻结';
                    $this->ajaxReturn($data);
                }

                $postCode = I('code');
                $code = session('orderCruiseInfoCode');

                if ($postCode == $code) {
                    $id = I('id');
                    $keyid = Utils::getDecrypt(I('keyid'));

                    if ($id != $keyid) {
                        $data['status'] = 0;
                        $data['msg'] = '提交失败';
                        $this->ajaxReturn($data);
                    }

                    session('orderCruiseInfoCode', null);

                    $tourInfo = M('tour')->where("id = '{$id}'")->find();
                    $data['tour_id'] = $id;
                    $data['agency_name'] = $userList['name'];
                    $data['tour_name'] = $tourInfo['name'];
                    $data['agency_id'] = $userList['id'];
                    $data['client_adult_count'] = I('client_adult_count');
                    $data['start_time'] = I('start_time');
                    $data['create_time'] = date('Y-m-d H:i:s', time());
                    $data['provider_id'] = $tourInfo['provider_id'];
                    $data['provider_name'] = $tourInfo['provider_name'];

                    $providerId['id'] = $tourInfo['provider_id'];
                    $providerInfo = M('provider')->where($providerId)->field('id,commission_rate,operator_id,full_name')->find();

                    $data['commission_rate'] = $providerInfo['commission_rate'];
                    $data['provider_operator_id'] = $providerInfo['operator_id'];
                    $data['agency_operator_id'] = $userList['operator_id'];
                    $data['provider_full_name'] = $providerInfo['full_name'];
                    $data['order_sn'] = substr(date("YmdHis", time()) . rand(1000, 9999), 2);
                    $where['start_time'] = I('start_time');
                    $where['tour_id'] = $tourInfo['id'];
                    //查找 top_tour_sku 表的提交日期信息
                    $sku_list = M('tour_sku')->where($where)->find();

                    $data['tour_sku_id'] = $sku_list['id'];
                    $data['price_adult'] = $sku_list['price_adult_agency'];
                    $data['contacts'] = I('contacts');
                    $data['contact_phone'] = I('contact_phone');
                    $data['memo'] = I('memo');
                    $data['state'] = Top::OrderStateSubmitted;

                    //计算成人、儿童总人数
                    $data['client_total'] = $data['client_adult_count'];

                    $adult_amount = $data['price_adult'] * $data['client_adult_count'];
                    //计算金额
                    $data['price_total'] = $adult_amount;
                    //将计算出的金额转成 **分
                    $totalMoney = $data['price_total'];

                    $result = $M->table('top_order_tour')->add($data);

                    $tourName = $tourInfo['name'];
                    $tourContactPhone = $tourInfo['contact_phone'];
                    $agencyName = $userList['name'];
                    $agencyId = $userList['id'];
                    $agencyNum = '(' . str_pad($agencyId, 4, '0', STR_PAD_LEFT) . ')';
                    $content = '您的' . $tourName . '线路已被代理商' . $agencyName . '' . $agencyNum . '预定，请登录系统查看';
                    Sms::Send($tourContactPhone, $content, $this->cdkey, $this->pwd, $this->signature, $this->smsOperatorId);

                    $tourOrderInfo = M('order_tour')->where("id = '{$result}'")->find();
                    $userInfo = M('user')->where("id = " . $tourInfo['user_id'])->find();
                    $notifyMsgTypes = explode(",", $userInfo['notify_msg_types']);
                    array_shift($notifyMsgTypes);
                    array_pop($notifyMsgTypes);
                    $transactionMessage = $notifyMsgTypes[1];

                    $template = array(
                        'touser' => $userInfo['weixinmp_openid'],
                        'template_id' => Utils::orderCreateSuccessTemplateId(),

                        'data' => array(
                            'first' => array('value' => urlencode($content), 'color' => "#000"),
                            'keyword1' => array('value' => urlencode($tourOrderInfo['order_sn']), 'color' => "#000"),
                            'keyword2' => array('value' => urlencode(Utils::getYuan($tourOrderInfo['price_total'])), 'color' => '#000'),
                            'keyword3' => array('value' => urlencode('已提交'), 'color' => '#000'),
                            'keyword4' => array('value' => urlencode($tourOrderInfo['create_time']), 'color' => '#000'),
                            'keyword5' => array('value' => urlencode($tourOrderInfo['tour_name']), 'color' => '#000'),
                            'remark' => array('value' => urlencode(''), 'color' => '#000'),
                        )
                    );

                    if ($transactionMessage) {
                        $this->send_tpl($template);
                    }

                    $orderLogData['order_id'] = $tourOrderInfo['id'];
                    $orderLogData['user_id'] = $tourOrderInfo['agency_id'];
                    $orderLogData['user_name'] = $tourOrderInfo['agency_name'];
                    $orderLogData['content'] = '代理商' . $agencyName . '下单';
                    $orderLogData['amount'] = 0;
                    $orderLogData['payable_total'] = $data['price_total'];
                    $orderLogData['create_time'] = date('Y-m-d H:i:s', time());
                    $orderLogData['payable_total'] = $totalMoney;
                    $orderLogData['remark'] = I('memo');

                    $orderLogResult = M('log_order_tour')->add($orderLogData);

                    if ($result && $orderLogResult) {
                        $data['status'] = 1;
                        $data['msg'] = '提交成功';
                        $this->ajaxReturn($data);
                    } else {
                        $data['status'] = 2;
                        $data['msg'] = '提交失败';
                        $this->ajaxReturn($data);
                    }
                } else {
                    $data['status'] = 3;
                    $data['msg'] = '请入重复提交';
                    $this->ajaxReturn($data);
                }
            } else {
                $id = I('id', 0, 'int');
                $today = date('Y-m-d 00:00:00');

                $list = $M->table('top_tour as t,top_tour_sku as s')
                    ->where("t.id = $id && t.id = s.tour_id && s.start_time >= '{$today}'")
                    ->field(array(
                        't.id' => 'id',
                        't.name' => 'name',
                        't.traffic_go' => 'traffic_go',
                        't.traffic_back' => 'traffic_back',
                        't.min_price' => 'min_price',
                        't.departure' => 'departure',
                        't.destination' => 'destination',
                        's.price_adult_agency' => 'price_adult_agency',
                    ))
                    ->find();

                $tourId = $list['id'];
                $list['price_adult_agency'] = Utils::getYuan($list['price_adult_agency']);

                //出游时间
                $tour_date = $M->table('top_tour_sku as s')
                    ->where("s.tour_id = '{$tourId}' && s.start_time >= '{$today}'")
                    ->field(array(
                        's.id' => 'id',
                        's.start_time' => 'start_time',
                    ))
                    ->select();

                $_SESSION['orderCruiseInfoCode'] = 400;

                $this->assign('userList', $userList);
                $this->assign('list', $list);
                $this->assign('tour_date', $tour_date);
            }
        } else {
            $domain = $_SERVER['SERVER_NAME'];
            $url = "http://" . $domain . "/index.php";
            header("Location:" . $url);
        }
        $this->display();
    }


    public function showQRCode()
    {
        $id = I('get.id');
        $url = "http://zhangda.m.lydlr.com/index.php/Home/Agency/details/id/{$id}.html";
        $level = 3;
        $size = 4;
        Vendor('phpqrcode.phpqrcode');
        $errorCorrectionLevel = intval($level);
        $matrixPointSize = intval($size);

        $object = new \QRcode();
        $object->png($url, false, $errorCorrectionLevel, $matrixPointSize);
    }

}
